package com.wallace.downloadserver.filter

import com.wallace.downloadserver.redis.RedisManager
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.core.RedisTemplate

/**
 * @Description:
 * 注册过滤器，控制过滤器的执行顺序
 * @author Wallace
 * @Date 2022/1/22 20:15
 */
@Configuration
class FilterConfig {

    private var redisAesKeyDB: RedisTemplate<String, Any>? = null

    @Autowired
    private fun setRedisAesKeyDB(redisManager: RedisManager) {
        redisAesKeyDB = redisManager.getAesKeyDB()
    }

    private var redisTokenDB: RedisTemplate<String, Any>? = null

    @Autowired
    private fun setRedisTokenDB(redisManager: RedisManager) {
        redisTokenDB = redisManager.getTokenDB()
    }

    @Bean(name = ["ParseTokenFilter"])
    fun registerDecryptFilter(): FilterRegistrationBean<ParseTokenFilter> {
        val filterRegistrationBean = FilterRegistrationBean<ParseTokenFilter>()
        filterRegistrationBean.filter = ParseTokenFilter(redisTokenDB)
        filterRegistrationBean.order = 1
        filterRegistrationBean.setName("ParseTokenFilter")
        filterRegistrationBean.urlPatterns = listOf("/downloadserver/api/*")
        // 排除预请求
        filterRegistrationBean.addInitParameter("excludedPaths", "/downloadserver/api/preRequest/.*")
        return filterRegistrationBean
    }

    @Bean(name = ["ParseBodyFilter"])
    fun registerTimeStampFilter(): FilterRegistrationBean<ParseBodyFilter> {
        val filterRegistrationBean = FilterRegistrationBean<ParseBodyFilter>()
        filterRegistrationBean.filter = ParseBodyFilter(redisAesKeyDB)
        filterRegistrationBean.order = 2
        filterRegistrationBean.setName("ParseBodyFilter")
        filterRegistrationBean.urlPatterns = listOf("/downloadserver/api/*")
        // 排除预请求
        filterRegistrationBean.addInitParameter("excludedPaths", "/downloadserver/api/preRequest/.*")
        return filterRegistrationBean
    }
}